package com.lancoo.ccas52.service.impl;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lancoo.ccas52.entity.UserSetting;
import com.lancoo.ccas52.mapper.UserSettingMapper;
import com.lancoo.ccas52.service.UserSettingService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author quin.song
 * @since 2023-01-06
 */
@Service
public class UserSettingServiceImpl extends ServiceImpl<UserSettingMapper, UserSetting> implements UserSettingService {

    @Override
    public UserSetting getUserSettingByUserId(String userId) {
        List<UserSetting> userSettingList = this.lambdaQuery().eq(UserSetting::getUserId, userId).list();
        //优先显示已设置任务配置 没有则显示第一条
        Optional<UserSetting> userSetting = userSettingList.stream().filter(a -> a.getIsCurrent().equals(1)).findFirst();
        if (!userSetting.isPresent()) {
            userSetting = userSettingList.stream().findFirst();
        }
        return userSetting.orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUserSetting(UserSetting userSetting) {
        //先更新所有任务为非当前任务
        this.update(new UserSetting().setIsCurrent(2), new LambdaQueryWrapper<UserSetting>()
                .eq(UserSetting::getUserId, userSetting.getUserId()));
        //再更新当前任务
        userSetting.setIsCurrent(1);
        boolean b = this.saveOrUpdate(userSetting, new LambdaQueryWrapper<UserSetting>()
                .eq(UserSetting::getUserId, userSetting.getUserId())
                .eq(UserSetting::getTaskId, ObjUtil.isNotNull(userSetting.getTaskId()) ? userSetting.getTaskId() : 0));
        return b;
    }

}
